import { login, getUserInfo } from '../../api/user'
var state = {
  token: localStorage.getItem('token') || '',
  user: localStorage.getItem('userDto') ? JSON.parse(localStorage.getItem('userDto')) : {}
}

var actions = {
  login({ commit }, params) {
    return new Promise((resolve, reject) => {
      login(params).then((res) => {
        console.log(res)
        localStorage.setItem('token', res.data.token)
        localStorage.setItem('accountNumber', params.accountNumber)
        localStorage.setItem('password', params.password)
        localStorage.setItem('userInfo', JSON.stringify(res.data.userInfo))
        commit('SET_TOKEN', res.data.token)
        commit('SET_USER', res.data.userInfo)
        resolve()
      }).catch(() => {
        reject()
      })
    })
  },
  getUserInfoByToken({ commit }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then((res) => {
        console.log(res)
        commit('SET_TOKEN', localStorage.getItem('token'))
        commit('SET_USER', res.data)
        resolve()
      }).catch(() => {
        reject()
      })
    })
  }
}

var mutations = {
  SET_TOKEN(state, params) {
    state.token = params
  },
  SET_USER(state, params) {
    state.user = params
  }
}

var getters = {

}

export default {
  namespaced: true,
  state,
  actions,
  mutations,
  getters
}

